<template>
  <div>
    <input
      class="input-item"
      v-model="showValue"
      @input="cursorChange"
      @keyup="cursorChange"
      @click="cursorChange"
      @mousedown="cursorChange"
      placeholder="请输入"
    />
    <div class="form-item">
      光标的前一个字符为：<span
        style="color: skyblue;font-size: 1.5em;font-weight: bold;"
        >{{ lastChar }}</span
      >
    </div>
  </div>
</template>

<script>
export default {
  name: "getLastChar",
  data() {
    return {
      showValue: "",
      lastChar: ""
    };
  },
  methods: {
    cursorChange(e) {
      const input = e.target;
      const value = input.value;
      const position = input.selectionStart;

      // 处理双字节字符
      const charArray = Array.from(value);

      let index = 0,
        resIndex = 0;
      while (index < position) {
        index += charArray[resIndex].length;
        resIndex++;
      }
      resIndex -= 1;
      this.lastChar = charArray[resIndex] || "";
    }
  }
};
</script>

<style>
.form-item {
  margin-top: 1em;
}
.input-item {
  margin-top: 1em;
  line-height: 1.5em;
  height: 1.5em;
  font-size: 1.2em;
  width: 20em;
  border: 1px solid #ccc;
}
</style>
